package com.stockz.equity.charting.painter.chart;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.List;

import org.springframework.stereotype.Component;

import com.stockz.equity.charting.util.MathUtil;
import com.stockz.equity.charting.view.StockChartPanelSkin;
import com.stockz.equity.charting.view.StockChartPanelState;
import com.stockz.equity.charting.view.StockChart;
import com.stockz.equity.model.Bar;

@Component
public class HLCBarChartPainter implements StockChartPainter {

	@Override
	public void paint(Graphics2D g, StockChart view, Rectangle rectangle) {
		StockChartPanelSkin stockChartPanelSkin = view.getStockChartPanel().getStockChartPanelSkin();
		StockChartPanelState stockChartPanelState = view.getStockChartPanel().getStockChartPanelState();
		g.setColor(stockChartPanelSkin.getBarColor());
		List<Bar> barList = stockChartPanelState.getBarList();
		for(int i = stockChartPanelState.getEndIndex()-1; i >= stockChartPanelState.getStartIndex(); i--){
			Bar bar = barList.get(i);
			if(i < barList.size()-1){
				Bar previous = barList.get(i+1);
				if(bar.getAveragePrice() < previous.getAveragePrice()){
					g.setColor(Color.red);
				}else{
					g.setColor(Color.green);
				}
			}
			
			int x = MathUtil.fitX(rectangle.x, 
					stockChartPanelState.getTimeUnitSpace(), 
					stockChartPanelState.getEndIndex(), 
					i);
			g.drawLine(
					x,
					MathUtil.fitY(rectangle.y, 
							rectangle.y+rectangle.height, 
							stockChartPanelState.getMinimumPriceVisible(), 
							stockChartPanelState.getMaximumPriceVisible(), 
							bar.getHigh(),
							stockChartPanelState.isSemiLog()),
					x,
					MathUtil.fitY(rectangle.y, 
							rectangle.y+rectangle.height, 
							stockChartPanelState.getMinimumPriceVisible(), 
							stockChartPanelState.getMaximumPriceVisible(), 
							bar.getLow(),
							stockChartPanelState.isSemiLog())
					);
			int closeY = MathUtil.fitY(rectangle.y, 
					rectangle.y+rectangle.height, 
					stockChartPanelState.getMinimumPriceVisible(), 
					stockChartPanelState.getMaximumPriceVisible(), 
					bar.getClose(),
					stockChartPanelState.isSemiLog());
			g.drawLine(
					x+stockChartPanelState.getTimeUnitSpace()/2,
					closeY,
					x,
					closeY
					);
			int avgPriceY = MathUtil.fitY(rectangle.y, 
					rectangle.y+rectangle.height, 
					stockChartPanelState.getMinimumPriceVisible(), 
					stockChartPanelState.getMaximumPriceVisible(), 
					bar.getAveragePrice(),
					stockChartPanelState.isSemiLog());
			g.drawLine(
					x+stockChartPanelState.getTimeUnitSpace()/2,
					avgPriceY,
					x-stockChartPanelState.getTimeUnitSpace()/2,
					avgPriceY
					);
		}
	}

	@Override
	public String toString() {
		return "High-Low-Close Bar";
	}
	
}
